package cn.midas.basic.service.impl;

import cn.midas.basic.dto.LoginDto;
import cn.midas.basic.exception.BusinessException;
import cn.midas.basic.service.ILoginService;
import cn.midas.basic.utils.MD5Utils;
import cn.midas.basic.utils.StrUtils;
import cn.midas.org.domain.Employee;
import cn.midas.org.mapper.EmployeeMapper;
import cn.midas.user.domain.Logininfo;
import cn.midas.user.mapper.LogininfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EmployeeMapper employeeMapper;

    public Long id;
    @Override
    public HashMap<String, Object> account(LoginDto loginDto) {
        String password = loginDto.getPassword();
        String username = loginDto.getUsername();
        Integer type = loginDto.getType();
        // 1.参数为空校验
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(username)
                || StringUtils.isEmpty(type)) {
            throw new BusinessException("参数为空，请重新填写！");
        }
        // 2.根据账号 type查询用户三个字段 username phone Email and type
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username, type);
        id = logininfo.getId();


        // 3.判断账号是否存在，不存在抛出异常
        if (logininfo == null) {
            throw new BusinessException("账号密码错误，请重新填写！");
        }
        // 4.判断密码是否一致，加盐加密比较
        String passwordTmp = MD5Utils.encrypByMd5( password +logininfo.getSalt());
        if (!logininfo.getPassword().equals(passwordTmp)) {
            throw new BusinessException("账号密码错误，请重新填写！");
        }
        // 5.生成uuid作为key
        String token = UUID.randomUUID().toString();
        // 6.将uuid 和 logininfo设置到redis中设置30分钟有效
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        // 7.把logininfo中敏感信息设为空作为value
        logininfo.setPassword("");
        logininfo.setSalt("");
        // 8.将uuid和logininfo存入map中返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;


    }
}
